#!/usr/bin/python
# -*- coding:utf-8 -*-

"""
代码简介：
使用 BeautifulSoup 和 re 模块来爬取金山词霸单词翻译的结果

对于输入的单词，获取相应的读音，释义，变形

对于输入的某些单词，可能并不能获取想要的结果，例如： hello world
原网页中是另一种类型，并没有对其做相应的处理，所以什么都爬取不到
"""

import urllib2
import re
from bs4 import BeautifulSoup

class JSCB(object):

    def __init__(self):
        self.headers = {'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
           'Referer' : 'http://www.iciba.com/'}
        self.url = "http://www.iciba.com/"
        self.result = None

    # 爬取页面
    def getHtml(self, word):
        request = urllib2.Request(self.url + word, headers= self.headers)
        response = urllib2.urlopen(request)
        # 返回经过lxml解析后的网页
        return BeautifulSoup(response.read().decode("utf-8"), "lxml")

    # 获取所查找单词的意思
    def contentWord(self, soup):
        self.result = []
        res = []
        # 获取音节
        mean1 = soup.find_all("div", class_="base-speak")
        pattern = re.compile(r'<span>.*?<span>(.*?)</span>.*?<span>.*?<span>(.*?)</span>', re.S)
        for mean in mean1:
            mean =  pattern.findall(str(mean))
            res.append(mean[0][0])
            res.append(mean[0][1])
            # print mean[0][0], mean[0][1]

        if len(res) != 0:
            self.result.append(res[:])
        res = []
        # 获取解释内容
        mean2 = soup.find_all("ul", class_="base-list switch_part")
        for mean in mean2:
            mean = mean.find_all("li", class_="clearfix")
            for mea in mean:
                mea = mea.find_all("span")
                for m in mea:
                    res.append(m.string)
                    # print m.string
                # res.append("\n")
                # print

        if len(res) != 0:
            self.result.append(res[:])
        res = [u"变形"]
        mean3 = soup.find_all("li", class_="change clearfix")
        pattern = re.compile(r'<span>(.*?)<a.*?>(.*?)</a>', re.S)
        for mean in mean3:
            for mea in pattern.findall(str(mean)):
                for m in mea:
                    res.append(m.strip())
                    # print m.strip()
                # print
                # res.append("\n")

        if len(res) > 2:
            self.result.append(res[:])
        if len(self.result) == 0:
            return None
        return self.result

    def start(self):
        flag = True
        while True:
            try:
                word = raw_input(u"输入要查找单词(输入为空或者都为空格结束)：")

                if len(word.strip()) == 0:
                    flag = False
                    break

                print u"查找单词为%s\n查找结果如下所示：\n" % word
                html = self.getHtml(word.strip())
                means = self.contentWord(html)
                # print means
                if means is None:
                    print u"对不起！没有找到相关的释义\n请检查输入是否合法"
                for mean in means:
                    for m in mean:
                        print m
                    print
            except Exception as e:
                # 接收可能出现的未知错误
                print u"输入出错, 错误原因为：", e
            finally:
                if flag == False:
                    break
                x = raw_input(u"请按任意键继续")

if __name__ == "__main__":
    a = JSCB()
    # print a.getHtml("hello")
    a.start()